package com.zj.core.dialog

import android.app.Activity
import android.os.Bundle
import android.text.Editable
import android.view.KeyEvent
import android.view.View
import android.widget.LinearLayout
import com.fileutils.BaseConstant
import com.systemutils.SystemUtil
import com.zj.core.R
import com.zj.core.tools.ViewPosition
import com.zj.core.ui.TemplateChangeUI
import android.text.TextWatcher
import com.fileutils.BaseConstant.*
import com.jniutils.DataCollUtil
import com.utils.DateUtils
import com.zj.core.base.BaseDialog
import com.zj.core.interfaces.ResultEmptyIml
import com.zj.core.interfaces.TemplateChangeIml
import com.zj.core.interfaces.TextMessageIml
import com.zj.core.tools.VoiceAsrTools
import com.zj.core.tools.VoiceFormatTools
import java.lang.StringBuilder
import java.util.regex.Pattern


@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class TemplateChangeDialog(activity: Activity?) : BaseDialog(activity), View.OnClickListener, TextMessageIml {
    private var mActivity: Activity? = activity
    private var callBackIml: TemplateChangeIml? = null
    private var mTemplateArr: ArrayList<String>? = ArrayList()
    private var rootView: TemplateChangeUI? = null
    private var mTemplateBuild: StringBuilder? = null
    private var mFormValueStr: String? = ""
    private var mDrugsList: String? = ""
    private var mLevelNurse: String? = ""
    private var mObjList: String? = ""
    private var mTemplateIndex = 0
    private var mPreviousLength: Int? = 0
    private var mHandle:VoiceAsrTools?=null
    private var mDismissResult:ResultEmptyIml?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val width: Int = ViewPosition().getScreenWidth(this.context)
        val height: Int = (ViewPosition().getScreenHeight(this.context) * 0.95).toInt()
        val params = LinearLayout.LayoutParams(width, height, 0f)
        rootView = TemplateChangeUI(context, this)
        rootView?.apply {
            setContentView(common_dialog_root_view, params)

            //setCancelable(cancelable)
            setCanceledOnTouchOutside(false)
            if (mTemplateArr?.get(0) != "") {
                common_dialog_title_tv?.text = mTemplateArr?.get(0)
            } else {
                common_dialog_title_tv?.text = "模板"
            }
            template_edit?.setLevelType(mLevelNurse.toString())
            template_edit?.addTextChangedListener(voiceStrChangeIml)
            template_edit?.setTextValue(0,mTemplateArr?.get(1).toString())
        }
        mTemplateBuild = StringBuilder()
        mHandle= VoiceAsrTools().setVoiceImage(rootView?.voiceImgView).setHandleListener(this)
    }

    fun setCallBackIml(callBackIml: TemplateChangeIml): TemplateChangeDialog {
        this.callBackIml = callBackIml
        return this
    }

    fun setNurseLevel(mLevelType: String): TemplateChangeDialog {
        this.mLevelNurse = mLevelType
        return this
    }

    fun setObjList(listStr: String): TemplateChangeDialog {
        this.mObjList = listStr
        return this
    }

    fun setDrugsList(drugsList: String): TemplateChangeDialog {
        this.mDrugsList = drugsList
        return this
    }

    fun setDismissIml(dismiss: ResultEmptyIml):TemplateChangeDialog{
        this.mDismissResult=dismiss
        return this
    }

    fun setTemplateValue(templateArr: ArrayList<String>): TemplateChangeDialog {
        this.mTemplateArr = templateArr
        return this
    }

    fun setTemplateIndex(index: Int): TemplateChangeDialog {
        this.mTemplateIndex = index
        return this
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        mHandle?.onKeyDown(keyCode,mActivity,rootView?.template_edit?.windowToken)
        return true
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        mHandle?.onKeyUp(keyCode,mActivity)
        return false
    }

    /**
     * 百度ASR数据返回
     */
    override fun messageResult(str: String){
        templateValueStr(str)
    }

    override fun onClick(v: View?) {
        mFormValueStr = ""
        when (v?.id) {
            R.id.common_dialog_cancel_tv -> dismiss()

            R.id.common_dialog_confirm_tv -> {
                callBackIml?.resultTemplateValue(
                    mTemplateArr?.get(0).toString(),
                    rootView?.template_edit?.text.toString(),
                    mTemplateIndex
                )
                dismiss()
            }
        }
    }

    /**
     * 文本录入框特殊字符处理
     */
    private val voiceStrChangeIml = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            mPreviousLength = s!!.length
        }

        override fun onTextChanged(s: CharSequence?, mStart: Int, mBefore: Int, mCount: Int) {}
        override fun afterTextChanged(s: Editable?) {
            if (mPreviousLength!! <= s!!.length) {
                tvInputSpace(s.toString())
            }
        }
    }

    /**
     * 正则匹配括号
     */
    private fun tvInputSpace(sourceStr: String) {
        var lastAdress = false
        SystemUtil.getGBKStrIndex(PATTERN_BLACKET, sourceStr).apply {
            if (size != 0) {
                val selectionIndex = (this[0].endIndex - this[0].startIndex) / 2 + this[0].startIndex
                rootView?.template_edit?.setSelection(selectionIndex)
                rootView?.template_edit?.requestFocus()
                lastAdress = true
            }
        }

        if (!lastAdress) {
            rootView?.template_edit?.setSelection(rootView?.template_edit?.text.toString().length)
            rootView?.template_edit?.requestFocus()
        }
    }

    /**
     * 模板内容  特殊字符处理
     */
    private fun templateValueStr(templateStr: String) {
        var mTimeValue: List<String>? = ArrayList()
        var objStr: String? = templateStr
        var mTimeStr: String? = ""
        var drugsIndex = 0
        mTemplateBuild?.clear()

        /**
         * 区间范围
         */
        val mSection = DataCollUtil.patternValue(PATTERN_SECTION, objStr)
        if (mSection != null && mSection != "") {
            objStr = objStr?.replace("[.|点|减|碘|斜杠|钢|\\-]".toRegex(), "/")?.replace("[到|道|导|盗]".toRegex(), "-")
        }

        /**
         * 时间匹配
         */
        val formatData = DateUtils.dateFormat(1, objStr,"")
        if (formatData != "" && DateUtils.isValidDate(formatData, "HH:mm")) {
            mTimeValue = formatData.split("|")
        }

        if (mTimeValue != null && mTimeValue.size > 1 && mTimeValue[1] == "") {    //只有时间项
            mTimeStr = mTimeValue[0]
            objStr = ""
        } else if (mTimeValue != null && mTimeValue.size == 1 && mTimeValue[0] != "") {    //只有时间项
            mTimeStr = mTimeValue[0]
            objStr = ""
        } else if (mTimeValue != null && mTimeValue.size > 1 && mTimeValue[1] != "") {     //时间项和数据项
            mTimeStr = mTimeValue[0]
            objStr = mTimeValue[1]
        }

        /**
         * 药品名称优先识别
         */
        mTemplateBuild?.append(VoiceFormatTools.drugFirstSolve(objStr.toString(),mDrugsList.toString()))


        /**
         * 体征数据项处理
         */
        val vitalSigns: String = mTemplateBuild.toString()
        mTemplateBuild?.clear()
        drugsIndex = 0
        val macher = DataCollUtil.getProjectList(BaseConstant.PATTERN_SPLITE, vitalSigns, mObjList)
        for (objBean2 in macher) {
            val value = objBean2.value
            val startIndex = vitalSigns.indexOf(value)

            val signs = Pattern.compile("($mObjList)").matcher(value)
            val result = if (signs.find()) {
                signs.group() + VoiceFormatTools.formatVoiceValue(signs.group(), value.replace(signs.group(), ""))
            } else {
                value
            }
            mTemplateBuild?.append(vitalSigns.substring(drugsIndex, startIndex) + result)
            drugsIndex = startIndex + value.length
        }
        mTemplateBuild?.append(vitalSigns.substring(drugsIndex, vitalSigns.length))

        val index = rootView?.template_edit?.selectionStart
        rootView?.template_edit?.setTextValue(index!!,mTimeStr +mTemplateBuild.toString())
    }

    override fun dismiss() {
        super.dismiss()
        mDismissResult?.resultValue()
    }
}